package com.hzya.frame.unifiedEntry.service.impl;


import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.extra.servlet.ServletUtil;
import com.hzya.frame.action.ApplicationContextUtil;
import com.hzya.frame.entity.BaseResult;
import com.hzya.frame.entity.JsonResultEntity;
import com.hzya.frame.exception.BaseSystemException;
import com.hzya.frame.unifiedEntry.service.IUnifiedEntryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Service(value = "unifiedEntryService")
public class UnifiedEntryServiceImpl implements IUnifiedEntryService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public JsonResultEntity doBusiness(ServletRequest servletRequest, ServletResponse servletResponse) throws InvocationTargetException, IllegalAccessException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String method = request.getMethod();
        //tailuo 要访问的Bean名称
        String service = request.getHeader("tl");
        //数据库表名称对于缓存的key
        String tableKey = request.getHeader("as");
        //bean方法
        String serviceMethod = request.getHeader("dj");
        /** 根据调用的 serviceMethod 获取相关table名称*/
        //String tableName = serviceMethodCache.get(tableKey);
        //
        //if (ObjectUtils.isEmpty(tableName)) {
        //    throw new BaseSystemException("根据tableKey获取tableName失败！未获取到数据！请检查参数tableKey。");
        //}
        String body = ServletUtil.getBody(servletRequest);
        //获取类
        Object object = null;
        try {
            object = ApplicationContextUtil.getBeanByName(service);
        } catch (SecurityException e) {
            return BaseResult.getFailureMessageEntity(service + "未找到");
        }
        //获取类下面的方法
        Method[] methods = object.getClass().getMethods();
        logger.info("methodsLength:" + methods.length);
        if (methods == null || methods.length == 0) {
            logger.info("当前methods:" + methods + "methodsLength = " + methods.length);

            return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法");
        } else {
            logger.info("当前methods222222:" + methods + "methodsLength = " + methods.length);

        }
        for (Method m : methods) {
            logger.info("当前mnAME:" + m.getName() + "   :serviceMethod = " + serviceMethod.trim());

            if (null != m) {
                if (m.getName().equals(serviceMethod.trim())) {
                    if (m.getName().startsWith("thirdInterface")) {//TODO 后续可能要加强校验规则
                        logger.info("第三方接口，不校验是否登陆");
                    } else if (!"doLogin".equals(m.getName())) {
                        try {
                            //TODO 暂时先不校验
                            //StpUtil.checkLogin();
                        }catch (NotLoginException e){
                            logger.error("token无效");
                            return BaseResult.getFailureMessageEntity("token无效");
                        }
                    }
                    logger.info("m.getNameEquals成功");

                    JSONObject jsonObject = new JSONObject();
                    if (!ObjectUtils.isEmpty(body)) {
                        jsonObject.put("jsonStr", body);
                    }
                    //jsonObject.put("tableName", tableName);

                    JsonResultEntity jsonResultEntity;
                    try {
                        logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        logger.info("请求的参数：jsonObject：" + jsonObject.toJSONString());
                        jsonResultEntity = (JsonResultEntity) m.invoke(object, jsonObject);
                        if (jsonResultEntity != null) {
                            jsonResultEntity.setType(serviceMethod);
                        }
                        logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        return jsonResultEntity;
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("METHOD doBusiness invokeException", e);
                        if (e instanceof InvocationTargetException) {
                            Throwable targetException = ((InvocationTargetException) e).getTargetException();
                            if (targetException instanceof BaseSystemException) {
                                throw new BaseSystemException(targetException.getMessage());
                            } else {
                                logger.info("METHOD doBusiness :", e);
                                e.printStackTrace();
                                throw e;
                            }
                        } else {
                            throw e;
                        }
                    }
                }
            }
        }
        return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法");
    }
}
